package com.example.websocket.web;

import com.alibaba.fastjson2.JSON;
import com.example.websocket.config.ResultVo;
import com.example.websocket.config.SocketConstant;
import com.example.websocket.config.SysUser;
import com.example.websocket.server.WebSocketServer;
import com.example.websocket.server.WebSocketServer2;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 测试Controller
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2024-03-04 17:58
 */
@RestController
@RequestMapping("/test")
public class TestController {

    /***
     * 主动推送消息给指定用户
     */
    @RequestMapping("/push/{userId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String userId) throws IOException {
        WebSocketServer.sendInfo(message, userId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }

    /***
     * 主动推送消息给所有用户
     */
    @RequestMapping("/pushAll")
    public ResponseEntity<String> pushAll(String message) throws IOException {
        for (String userId : WebSocketServer.getWebSocketMap().keySet()) {
            WebSocketServer.sendInfo(message, userId);
        }
        return ResponseEntity.ok("MSG SEND ALL SUCCESS");
    }

    @RequestMapping("/push1/{username}")
    public ResponseEntity<String> push1ToWeb(String message, @PathVariable String username) throws IOException {
        ResultVo<String> ok = ResultVo.ok(SocketConstant.GENERIC_MSG_TYPE, message);
        WebSocketServer2.sendInfo(message, JSON.toJSONString(ok));
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }

    @RequestMapping("/pushAll2")
    public ResponseEntity<String> pushAll2(String message) throws IOException {
        ResultVo<String> ok = ResultVo.ok(SocketConstant.GENERIC_MSG_TYPE, message);
        String jsonString = JSON.toJSONString(ok);
        WebSocketServer2.getWebSocketMap().forEach((k, v) -> {
            SysUser user = WebSocketServer2.getTokenUserMap().get(k);
            WebSocketServer2.sendInfo(jsonString, user.getUsername());
        });
        return ResponseEntity.ok("MSG SEND ALL SUCCESS");
    }

}
